package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.enums.SeeRecordEnums;
import one.stand.model.*;
import one.stand.request.SeeRecordRequest;
import one.stand.response.CrmCustomerAnalysisRespnse;
import one.stand.response.CrmSeeRecordResponse;
import one.stand.response.CustomerAnalysisResponse;
import one.stand.service.BaseService;
import one.stand.service.SeeRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Administrator
 */
@Service
public class SeeRecordServiceImpl extends BaseService implements SeeRecordService {
    @Override
    public ResultModel<Map<String,Object>> customerAnalysis(SeeRecordRequest recordRequest) {
        log.info("客户与我的互动:{}", JSON.toJSONString(recordRequest));
        if(recordRequest == null){
            return ResultModel.checkParamFail();
        }
        if(recordRequest.getType() == null){
            recordRequest.setType(2);
        }
        // 客户与自己的沟通次数
        Long imNum = consultRecordMapper.count(new ConsultRecordModel(){{
            if(recordRequest.getUserId() != null){
                setUserId(recordRequest.getUserId().intValue());
            }
            if(recordRequest.getType() == 1){
                setCompanyCardId(recordRequest.getMyCardId().intValue());
            }else if(recordRequest.getCardId() != null){
                setCompanyCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        // 获取客户拨打我的电话次数
        Long callsNum = callsPhoneRecordMapper.count(new CallsPhoneRecordModel() {{
            if(recordRequest.getUserId() != null){
                setUserId(recordRequest.getUserId().intValue());
            }
            if(recordRequest.getType() == 1){
                setCompanyCardId(recordRequest.getMyCardId().intValue());
            }else if(recordRequest.getCardId() != null){
                setCompanyCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        //商品转发次数
        Long goodForwardNum = goodsForwardRecordMapper.count(new GoodsForwardRecordModel() {{
            if(recordRequest.getUserId() != null){
                setUserId(recordRequest.getUserId().intValue());
            }
            if(recordRequest.getType() == 1){
                setCompanyCardId(recordRequest.getMyCardId().intValue());
            }else if(recordRequest.getCardId() != null){
                setCompanyCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        //评论次数
        Long commentNum=commentMapper.count(new CommentModel(){{
            if(recordRequest.getUserId() != null){
                setUserId(recordRequest.getUserId().intValue());
            }
            if(recordRequest.getType() == 1){
                setCardId(recordRequest.getMyCardId().intValue());
            }else if(recordRequest.getCardId() != null){
                setCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        //文章转发次数
        Long dynamicNum=dynamicForwardRecordMapper.count(new DynamicForwardRecordModel(){{
            if(recordRequest.getUserId() != null){
                setUserId(recordRequest.getUserId().intValue());
            }
            if(recordRequest.getType() == 1){
                setCompanyCardId(recordRequest.getMyCardId().intValue());
            }else if(recordRequest.getCardId() != null){
                setCompanyCardId(recordRequest.getCardId());
            }
            setCompanyId(recordRequest.getCId().intValue());
        }});
        //客户信息
        CustomerAnalysisResponse analysisModel = new CustomerAnalysisResponse();
        if(recordRequest.getUserId() != null){
            // 员工卡片，客户id，查看类型（2产品）
            analysisModel = seeRecordMapper.getCustomerAnalysis(recordRequest.getMyCardId(), recordRequest.getUserId().intValue(), SeeRecordEnums.PRODUCT.getCode(),recordRequest.getCId().intValue());
            analysisModel.setName(StringUtils.isBlank(analysisModel.getName())?"":new String(Base64.getDecoder().decode(analysisModel.getName().getBytes())));
        }
        Map<String,Object> data=new HashMap<>(8);
        data.put("imNum",imNum);
        data.put("callsNum",callsNum);
        data.put("goodForwardNum",goodForwardNum);
        data.put("commentNum",commentNum);
        data.put("dynamicNum",dynamicNum);
        data.put("analysisModel",analysisModel);
        return ResultModel.success(data);
    }

    @Override
    public ResultModel<List<CrmSeeRecordResponse>> getSeeRecordList(SeeRecordRequest recordRequest) {
        log.info("ai分析：{}", JSON.toJSONString(recordRequest));
        if (recordRequest.getEntranceType() == null) {
            return ResultModel.checkParamFail();
        }
        //ai分析验证 和行为追踪都需要查看类型
        if (recordRequest.getEntranceType() == 3 || recordRequest.getEntranceType() == 2) {
            if (recordRequest.getSeeType() == null) {
                return ResultModel.checkParamFail();
            }
        }
        //时间追踪不需要查看类型
        if (recordRequest.getEntranceType() == 1 || recordRequest.getEntranceType() == 4) {
            recordRequest.setSeeType(null);
        }
        PageHelper.startPage(recordRequest.getPageNum(), recordRequest.getPageSize());
        List<CrmSeeRecordModel> crmSeeRecordModels = seeRecordMapper.getCrmSeeRecord(recordRequest.getUserId(), recordRequest.getEntranceType(), recordRequest.getSeeType(),recordRequest.getMyCardId());
        PageInfo<CrmSeeRecordModel> pageInfo = new PageInfo(crmSeeRecordModels);
        List<CrmSeeRecordResponse> crmSeeRecordResponseList = new ArrayList<>();
        pageInfo.getList().forEach(c -> {
            CrmSeeRecordResponse recordResponse = new CrmSeeRecordResponse();
            BeanUtils.copyProperties(c, recordResponse);
            recordResponse.setNickName(StringUtils.isBlank(c.getNickName())?"":new String(java.util.Base64.getDecoder().decode(c.getNickName())));
            recordResponse.setName(recordResponse.getNickName());
            crmSeeRecordResponseList.add(recordResponse);
        });
        return ResultModel.success(crmSeeRecordResponseList);
    }

    @Override
    public ResultModel<List<CrmCustomerAnalysisRespnse>> countCustomerAnalysis(SeeRecordRequest recordRequest) {
        log.info("圆饼图：{}", JSON.toJSONString(recordRequest));
        if(recordRequest == null){
            return ResultModel.checkParamFail();
        }
        SeeRecordModel model = new SeeRecordModel();
        BeanUtils.copyProperties(recordRequest,model);
        if(recordRequest.getCardId() == null){
            model.setCardId(recordRequest.getMyCardId());
        }else if(recordRequest.getType() != null && recordRequest.getType() == 1){
            model.setCardId(recordRequest.getCardId());
        }
        if(recordRequest.getUserId() != null) {
            model.setUserId(recordRequest.getUserId().intValue());
        }
        model.setCompanyId(recordRequest.getCId().intValue());
        List<CrmCustomerAnalysisRespnse> list = seeRecordMapper.countCustomerAnalysis(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        return ResultModel.success(list);
    }

    @Override
    public ResultModel<Map<String, Object>> getPcCount(SeeRecordRequest request) {
        log.info("CRM-PC端首页统计:{}", JSON.toJSONString(request));
        if(request == null){
            return ResultModel.checkParamFail();
        }
        SeeRecordModel model = new SeeRecordModel();
        if(ONE.equals(request.getType())){
            model.setCardId(request.getMyCardId().intValue());
        }else{
            model.setCompanyId(request.getCId().intValue());
        }
        Map<String, Object> map = seeRecordMapper.getPcCount(model);
        if(map == null){
            return ResultModel.noData();
        }
        // 查询未跟进客户头像-最多5张
        map.put("photos",seeRecordMapper.getPcPhotos(model));
        // 查询今日录入客户列表
        map.put("newCustomerList",seeRecordMapper.selectPcIndexCustomer(model));
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<Map<String, Object>> getChangeCount(SeeRecordRequest request) {
        log.info("CRM-PC端首页转化率漏斗:{}", JSON.toJSONString(request));
        if(request == null){
            return ResultModel.checkParamFail();
        }
        SeeRecordModel model = new SeeRecordModel();
        if(ONE.equals(request.getType())){
            model.setCardId(request.getMyCardId().intValue());
        }
        if(request.getDayNum() == null){
            model.setDayNum(30);
        }else{
            model.setDayNum(request.getDayNum());
        }
        model.setCompanyId(request.getCId().intValue());
        Map<String, Object> list = seeRecordMapper.getChangeCount(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        model.setSeeType(2);
        list.put("seeGoodsNum",seeRecordMapper.getChangeCountOne(model));
        return ResultModel.success(list);
    }
}
